# -*-* encoding:UTF-8 -*-
# author            : mengy
# date              : 2018/12/13
# python-version    : Python 3.7.0
# description       : 协议命令解释器

class CommandHandler:
    "命令处理类"

    def unknown(self, session, cmd):
        "响应未知命令"
        session.push(('Unknown command {} \n'.format(cmd)).encode('utf-8'))

    def handle(self, session, line):
        line = str(line.decode())
        # 命令处理
        if not line.strip():
            return
        parts = line.split(' ', 1)
        cmd = parts[0]
        try:
            line = parts[1].strip()  # 去除首尾空格
        except Exception as e:
            line = ''
            print('命令处理发生异常，原因:', e)

        # 通过协议代码执行相应的方法
        method = getattr(self, 'do_' + cmd, None)
        try:
            method(session, line)
        except TypeError as e:
            self.unknown(session, cmd)
            print('方法调用异常，原因:', e)
